package com.ruoyi.web.controller.sse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.sse.SseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * SSE Controller
 * @author qjy
 */
@RestController
@Slf4j
@RequestMapping("/sse")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "SSE")
public class SseController {

    private final SseUtils sseUtils;

    @ApiOperation("创建连接")
    @Anonymous
    @GetMapping(value = "/createSseConnect", produces="text/event-stream;charset=UTF-8")
    public SseEmitter createSseConnect(@RequestParam(name = "clientId", required = false) Long clientId) {
        return sseUtils.connect(clientId);
    }


    @ApiOperation("发送消息")
    @Anonymous
    @PostMapping("/sendMessage")
    public void sendMessage(@RequestParam("clientId") Long clientId, @RequestParam("message")  String message){
        boolean b = sseUtils.sendMessage(clientId, "123456789", message);
        log.info("sendMessage result:{}", b);
    }

    @ApiOperation("获取连接列表")
    @Anonymous
    @GetMapping(value = "/listSseConnect")
    public AjaxResult listSseConnect(){
        Map<Long, SseEmitter> sseEmitterMap = sseUtils.getSseEmitterMap();
        sseEmitterMap.forEach((key,value) -> log.info("sseEmitterMap key:{}, value:{}", key, value));
        return success(sseEmitterMap);
    }


    /**
     * 关闭SSE连接
     *
     * @param clientId 客户端ID
     **/
    @ApiOperation("关闭SSE连接")
    @Anonymous
    @GetMapping("/closeSseConnect")
    public AjaxResult closeSseConnect(Long clientId) {
        sseUtils.deleteUser(clientId);
        return success();
    }


}
